﻿using System;
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LightCAD.MathLib
{
    /// <summary>
    /// 圆锥面
    /// </summary>
    public class ConicalSurface3d : Surface3d
    {
        public double Radius { get; private set; }
        public double Height { get; private set; }
        public double StartAngle { get; private set; }
        public double EndAngle { get; private set; }
        public bool IsClosed { get; private set; }

        public ConicalSurface3d(double radius, double height, double startAngle, double endAngle, bool isClose = true)
        {
            this.Radius = radius;
            this.Height = height;
            this.StartAngle = startAngle;
            this.EndAngle = endAngle;
            this.IsClosed = isClose;

            var arc = new Arc3d(new Vector3(), radius, startAngle, endAngle);
            var topVertex = new Vector3(0, 0, this.Height);
            this.OuterLoop = new List<Curve3d>
            {
                new Line3d(topVertex, arc.Start),
                arc,
                new Line3d(arc.End, topVertex),
            };
        }

        public override Tuple<double[], int[]> Trianglate()
        {
            var topVertex = this.OuterLoop[0].Start;
            var allPoints = new ListEx<Vector3>();
            var indices = new ListEx<int>();
            var btmPoints = this.OuterLoop[1].GetPoints(Cone3d.TempSegments);

            for (int i = 0; i < btmPoints.Count; i++)
            {
                var count = allPoints.Count;
                var nxi = i + 1;
                if (nxi == btmPoints.Count)
                {
                    if (!IsClosed)
                    {
                        break; //已经到了最后一片
                    }
                    else
                    {
                        nxi = 0;
                    }
                }

                indices.Push(count, count + 1, count + 2);
                allPoints.Push(topVertex, btmPoints[i], btmPoints[nxi]);
            }

            var posArr = Utils.GenerateVertexArr(allPoints);
            return new Tuple<double[], int[]>(posArr, indices.ToArray());
        }
    }
}
